package com.tencent.wxcloudrun.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.tencent.wxcloudrun.config.ApiResponse;
import com.tencent.wxcloudrun.dto.CosAuthResponse;
import com.tencent.wxcloudrun.dto.DownLoadLinkInfo;
import com.tencent.wxcloudrun.dto.UploadLinkInfo;
import com.tencent.wxcloudrun.model.User;
import com.tencent.wxcloudrun.service.TxCosService;
import com.tencent.wxcloudrun.service.UserService;
import com.tencent.wxcloudrun.utils.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Collections;
import java.util.Optional;

@RestController
@RequestMapping("/file")
public class FileController {

    private final TxCosService txCosService;

    private final UserService userService;

    private final Logger logger;

    public FileController(TxCosService txCosService, UserService userService) {
        this.txCosService = txCosService;
        this.userService = userService;
        this.logger = LoggerFactory.getLogger(FileController.class);
    }

    @GetMapping("/cos/auth")
    public ApiResponse getCosAuth(@RequestHeader("Authorization") String token) {
        if (token == null || token.isEmpty()) {
            return ApiResponse.authError("未登录");
        }

        String mobile = JwtUtil.parseToken(token);
        if (mobile == null) {
            return ApiResponse.authError("登录已过期，请重新登录");
        }

        Optional<User> user = userService.findByMobile(mobile);
        if (!user.isPresent()) {
            return ApiResponse.authError("用户未找到，请重新登录");
        }
        try {
            CosAuthResponse res = txCosService.getCosAuthSignConfig();
            return ApiResponse.ok(res);
        } catch (Exception e) {
            logger.error(StrUtil.format("获取COS秘令失败:{}", e.getMessage()), e);
            return ApiResponse.error("获取COS授权失败");
        }
    }

//    @PostMapping("/cos/upload")
//    public ApiResponse uploadFile(@RequestHeader("Authorization") String token, @RequestParam("fileKey") String fileKey, @RequestParam("file") MultipartFile file) throws IOException {
//        if (token == null || token.isEmpty()) {
//            return ApiResponse.authError("未登录");
//        }
//
//        String mobile = JwtUtil.parseToken(token);
//        if (mobile == null) {
//            return ApiResponse.authError("登录已过期，请重新登录");
//        }
//
//        Optional<User> user = userService.findByMobile(mobile);
//        if (!user.isPresent()) {
//            return ApiResponse.authError("用户未找到，请重新登录");
//        }
//        String path = StrUtil.format("scb/{}/{}", user.get().getId(), fileKey);
//        UploadLinkInfo uploadLinkInfo = txCosService.getUploadLink(path);
//        String fileUrl = txCosService.uploadFile1(uploadLinkInfo, file);
//        return ApiResponse.ok(fileUrl);
//    }


    @GetMapping("/upload/url")
    public ApiResponse getUploadUrl(@RequestParam("fileName") String fileName) {
        String path = StrUtil.format("scb/{}/{}/{}", DateUtil.thisYear(), DateUtil.thisMonth() + 1, fileName);
        UploadLinkInfo uploadLinkInfo = txCosService.getUploadLink(path);
        txCosService.uploadLinkInfo = uploadLinkInfo;
        return ApiResponse.ok(uploadLinkInfo);
    }

    @GetMapping("/download/url")
    public ApiResponse getDownloadUrl(@RequestParam("fileId") String fileId) {
        DownLoadLinkInfo downLoadLinkInfo = txCosService.getDownloadUrls(Collections.singletonList(fileId));
        return ApiResponse.ok(downLoadLinkInfo);
    }


    @PostMapping("/cos/upload")
    public ApiResponse uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
//        String path = StrUtil.format("scb/{}", file.getOriginalFilename());
//        UploadLinkInfo uploadLinkInfo = txCosService.getUploadLink(path);
//        txCosService.uploadLinkInfo = uploadLinkInfo
        String fileUrl = txCosService.uploadFile1(txCosService.uploadLinkInfo, file);
        return ApiResponse.ok(fileUrl);
    }


}
